from ib.ext.EWrapper import EWrapper
from ib.ext.EClientSocket import EClientSocket
from ib.ext.Contract import Contract

import IBFactory

import random

verbose = False

gfile = open('c:/junk/scratch.txt','r+')

gcount = 0

def printPrice(price):
    global gcount
    global gfile

    if (gcount < 2):
        gfile.write('call bid: %s\n' %(price))
        gcount+=1
    if (gcount == 2):
        gfile.close()

    


class PrintWrapper(EWrapper):
    def tickPrice(self, tickerId, field, price, canAutoExecute):
        printPrice(price)
        
    def tickSize(self, tickerId, field, size):
        if( verbose):
            print 'sizeMsg\n'

    def tickString(self, tickerId, tickType, value):
        if( verbose): 
            print 'tickStringMsg'

    def tickSnapshotEnd(self, tickerId):
        """ not working for now"""
        print "FINITO"
        gfile.close()
    def tickOptionComputation(self, tickerId, field, impliedVolatility, delta):
        print delta

    def nextValidId(self, orderId):
        print orderId

    def error(self, id=None, errorCode=None, errorMsg=None):
        print errorMsg


    


handler = PrintWrapper()
connection = EClientSocket(handler)
connection.eConnect('localhost', 7496, 0)

contract = Contract()
contract.m_symbol = 'SPY' 
contract.m_exchange = 'SMART'
contract.m_currency = 'USD'
contract.m_secType = 'STK'

tickerId = random.randint(1,999)
connection.reqMktData(tickerId, contract, "", True)
#connection.eDisconnect()
